import { defineStore } from "pinia";
import {
  listMsgPage, // 消息列表分页
  editMsg, // 编辑消息
  delMsg, // 删除消息
} from "@/utils/api/message/message";
import { useMemberStore } from "@/stores/modules/member";
import { useToastStore } from "@/stores/modules/toast";
export const useMessageStore = defineStore(
  "message",
  () => {
    const toastStore = useToastStore();
    // 当前显示的消息详情
    let showMsgItem: any = ref("");
    //显示列表or详情
    let showType: any = ref("list");
    // All消息列表
    let msgList: any = [];
    let messageBox: any = reactive({ msgList });
    // 工作台消息列表
    let WorkbenchMsgList: any = [];
    let WorkbenchMsgBox: any = reactive({ WorkbenchMsgList });
    const userStore = useMemberStore();
    // 获取消息列表
    const getMessageList = async (data: any) => {
      const res = await listMsgPage({
        Addressee: userStore.user_id,
        pageNum: data.pageNum || 1,
        pageSize: data.pageSize || 10,
        MsgStatus: data.MsgStatus,
        MsgType: "",
      });
      if (data.MsgStatus) {
        WorkbenchMsgBox.WorkbenchMsgList = res.data.list;
      } else {
        messageBox.msgList = res.data.list;
      }
      let total = res.data.totalCount;
      console.log("message 消息列表", res);
      return total;
    };
    // 消息修改查询
    const editFindMsgList = async (data: any) => {
      const res = await editMsg(data);
      console.log("message 消息查询", res);
      showMsgItem.value = res.data;
      return res;
    };
    // 删除消息
    const delFindMsgList = async (data: any) => {
      const res = await delMsg({
        MsgCode: data.MsgCode,
      });
      await getMessageList({});
      toastStore.show = true;
      toastStore.type = "success";
      toastStore.title = "删除成功";
      getMessageList({ MsgStatus: "MsgUnread" });
      console.log("message 删除消息", res);
      return res;
    };
    return {
      showMsgItem,
      messageBox,
      getMessageList,
      WorkbenchMsgBox,
      delFindMsgList,
      showType,
      editFindMsgList,
    };
  },
  /***************** TODO: 持久化****************** */
  {
    // 配置持久化
    persist: {
      // 调整为兼容多端的API
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value);
        },
        getItem(key) {
          return uni.getStorageSync(key);
        },
      },
      paths: ["message", "WorkbenchMsgBox"],
    },
  }
);
